package cn.edu.hitwh.kanlema.config;

import cn.edu.hitwh.kanlema.dto.Result;
import cn.edu.hitwh.kanlema.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class WebExceptionAdvice {
    @ExceptionHandler(ApiException.class)
    public ResponseEntity<Result> handleApiException(ApiException e) {
        // log.error(e.toString(), e);
        return ResponseEntity.status(e.getCode()).body(Result.fail(e.getMessage()));
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Result> handleConstraintViolationException(ConstraintViolationException e) {
        // log.error(e.toString(), e);
        Result result = Result.fail("服务异常");
        e.getConstraintViolations().stream().findFirst().ifPresent(violation -> {
            result.setErrorMsg(violation.getMessage());
        });
        return ResponseEntity.status(400).body(result);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handleException(Exception e) {
        log.error(e.toString(), e);
        return ResponseEntity.status(500).body(Result.fail("服务异常"));
    }
}
